<?php
Namespace Cyfy\Modules\Forms;
use Cyfy\Message;
use Cyfy\Modules\Locale\Locale;

/**
 * Input type = password, text class.
 *
 * You can validate it when $format is set.
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class TextBox extends Input
{
    /**
     * Maximum length for the input.
     * @var int
     */
    public $maxLength = 50;
    
    /**
     * Minimum length for the input.
     * @var int
     */
    public $minLength = 1;
    
    /**
     * Maximum value of the input. Applies only when $format = number.
     * @var int
     */
    public $maxValue = 0;
    
    /**
     * Minimum value the input. Applies only when $format = number.
     * @var int
     */
    public $minValue = 0;
    
    /**
     * Whether this is password.
     * @var bool
     */
    public $password = false;
    
    /**
     * Whether disable autocompletion.
     * @var bool
     */
    public $disableAutocomplete = false;
    
    /**
     * String format, can be empty, "number", "email", "datetime"
     * @var bool
     */
    public $format = "";
    
    
    /**
     * Creates a new input element.
     *
     * @param string Textbox name
     * @param string Title
     * @param string Default value
     * @param bool Is required
     * @param int Maximum length
     * @param int Minimum length
     */
    function __construct($name, $title, $value = '', $required = false, $maxLength = 50, $minLength = 1)
    {
        $this -> name = $name;
        $this -> title = $title;
        $this -> value = $value;
        $this -> required = $required;
        $this -> maxLength = $maxLength;
        $this -> minLength = $minLength;
    }
    
    
    /**
     * Returns a string containing the input.
     * @return string HTML content
     */
    function __toString()
    {
        // if description -> show popup
        $this -> loadDescription();        
        
        // values
        $maxLength = ($this -> maxLength) ? "maxlength=\"{$this -> maxLength}\"" : "";
        $type = ($this->password) ? "password" : "text";
        $required = ($this->required) ? " form-validate" : "";
        $star = ($this->required) ? \Cyfy\Modules\Forms\Module :: REQUIRED_CHAR : "";
        $disableAutocomplete = ($this->disableAutocomplete) ? " autocomplete=\"off\"" : "";
        
        $id = "";
        // if format == datetime, show datepicker
        if($this -> format == "datetime")
        {
            $id = "date_" . uniqid();
            \Cyfy\Modules\jquery\Plugins :: load("jqueryUI");
            \Cyfy\Modules\jquery\Plugins :: load("jqueryTimepicker");
            
$js = <<<JS
$(document).ready(function(){
    $("#{$id}" ).datetimepicker({dateFormat: 'yy-mm-dd', separator: ' ', timeFormat: 'hh:mm:ss' });
});
JS;
            \Cyfy\Cyfy ::  JavaScript($js, "inline", "header");
            
            $id = " id=\"{$id}\" ";
        }
        
        // html
        $output = "<div class=\"form-item form-item-{$this->name}\"> \n";
        $output .= "    <label class=\"form-label-{$this->name}{$required}\" title=\"{$this->description}\" for=\"{$this->name}\">".$this -> title.": {$star}</label> \n";
        $output .= "	<input type=\"$type\" class=\"form-input-{$this->name}\" name=\"{$this->name}\" value=\"{$this->value}\" {$id}{$maxLength}{$disableAutocomplete}/>";
        $output .= "</div> \n\n";
        return $output;
    }
    
    
    /**
     * Checks, whether the input matches format.
     * @return bool
     */
    private function checkFormat()
    {
        switch($this -> format)
        {
            /* NUMBER */
            case "number":
                $n = $this -> value;
                
                // is number??
                if(!is_numeric($n)){
                    Message :: set(\Cyfy\Modules\Forms\Module :: t(141, array($this->title)), Message::ERROR);
                    return false;
                }	
                
                // is integer? if necessary ??
                if(!((integer) $n == $n)){
                    Message :: set(\Cyfy\Modules\Forms\Module :: t(151, array($this->title)), Message::ERROR);
                    return false;
                }	
                
                // too high?
                if($this -> maxValue){
                    if($n > $this->maxValue){
                        Message :: set(\Cyfy\Modules\Forms\Module :: t(161, array($this->title, $this->maxValue)), Message::ERROR);
                        return false;
                    }
                }	
                // too low?
                if($this -> minValue){
                    if($n < $this->minValue){
                        Message :: set(\Cyfy\Modules\Forms\Module :: t(171, array($this->title, $this->minValue)), Message::ERROR);
                        return false;
                    }
                }
                break;
            
            case "datetime":
                try{
                    $datetime = new \Datetime($this -> value);
                }catch(Exception $e)
                {
                    Message :: set(\Cyfy\Modules\Forms\Module :: t(180), Message::ERROR);
                    return false;
                }
                break;
                
             case "email":
                if(!filter_var($this->value, FILTER_VALIDATE_EMAIL)){
                    
                    Message :: set(\Cyfy\Modules\Forms\Module :: t(211, array($this->value)), Message::ERROR);
                }
                break;
                
            case "":
                break;
                
                //regex
            default:
                if(!preg_match($this->format, $this -> value))
                {
                    Message :: set(\Cyfy\Modules\Forms\Module :: t(231, array($this->title)), Message::ERROR);
                    return false;
                }
        }
        return true;
    }
    
    /**
     * Loads data from post to the object.
     * Fixes some security stuff.
     *
     * @return array array(name => value)
     */
    function loadPostData($prefix)
    {
        // load
        $this -> value = $_POST[$prefix . $this -> name];
        
        // security
        $this -> value = strip_tags($this -> value);
        
        return array($this -> name => $this -> value);
    }
    
    /** 
     * Validates the data.
     * @return bool
     */
    function validate()
    {
        if($this -> value){
            // too long?
            if($this -> maxLength !== null){
                if(strlenUTF8($this->value) > $this->maxLength){
                        Message :: set(\Cyfy\Modules\Forms\Module :: t(181, array($this->title, $this->maxLength)), Message::ERROR);
                    return false;
                }
            }	
            // too short?
            if($this -> minLength !== null){
                if(strlenUTF8($this->value) < $this->minLength){
                        Message :: set(\Cyfy\Modules\Forms\Module :: t(191, array($this->title, $this->minLength)), Message::ERROR);
                    return false;
                }
            }
            
            // format
            if(!$this -> checkFormat())
            {
                return false;
            }
        }
        // required
        if($this->required){
            if($this -> value == ""){
                Message :: set(\Cyfy\Modules\Forms\Module :: t(201, array($this->title)), Message::ERROR);
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }
}